import { Component, OnInit } from '@angular/core';

import {StorageService} from "../../services/storage.service";

@Component({
  selector: 'app-todo-list',
  templateUrl: './todo-list.component.html',
  styleUrls: ['./todo-list.component.scss']
})
export class TodoListComponent implements OnInit {

  public keyword;

  public todoList=[];

  constructor(public storage:StorageService) {
    // let s = this.storage.get()
    // console.log(s)
  }

  ngOnInit(): void {
    let todoList = this.storage.get('todoList')

    if(todoList) {
      this.todoList = todoList
    }
  }

  doAdd(e) {
    if(e.keyCode==13) {

      if(!this.todoListHasKeyword(this.todoList, this.keyword)) {
        this.todoList.push({
          title: this.keyword,
          status: 0       // 0 表示代办事项   1表示已完成事项
        })
        this.keyword = ''
        this.storage.set('todoList', this.todoList)  //一定要注意this的指向问题
      } else {
        alert("数据已经存在")
        this.keyword=''
      }

    }
  }

  deleteData(key) {
    this.todoList.splice(key, 1)

    this.storage.set('todoList', this.todoList)  //一定要注意this的指向问题
  }
  // 如果数组里面有keyword返回true，否则返回false
  todoListHasKeyword(todoList, keyword) {
    //异步会有问题
    // todoList.forEach(value => {
    //   if(value.title==keyword) {
    //     return true;
    //   }
    // })
    if(!keyword) return false;

    for(let i=0;i<todoList.length;i++) {
        if(todoList[i].title==keyword) {
          return true;
        }
    }
    return false;
  }

  checkboxChange() {
    console.log('改变事件触发了')

    this.storage.set('todoList', this.todoList)  //一定要注意this的指向问题
  }
}
